from cron_converter import Cron
import json5, time, datetime, functools
from lxml import etree
import sqlite3, os, feedparser, linecache, re

class Config(object):
    def __init__(self, url, xpath=None):
        self.url = url
        self.xpath = xpath

    def load_config(self, config_file):
        # print(f"DEBUG: load config {config_file}")
        with open(config_file,'r',encoding='utf8')as fp:
            config = json5.load(fp)
            return config

    def getDiff_prevCron_now(self, cron_str: str):
        if cron_str:
            cron_instance = Cron(cron_str)
            now = datetime.datetime.now()
            schedule = cron_instance.schedule(now)
            prev_dt = schedule.prev()
            diff = (now-prev_dt).total_seconds()
            return diff
        else:
            return None



class DbHelper(object):
    GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'
    def __init__(self, db_name='novel.db'):
        self.conn = sqlite3.connect(db_name)

    def insert_chapters(self, code, links):
        cur = self.conn.cursor()
        sql_text_2 = "INSERT INTO NOVEL(CODE,LINK,TITLE) VALUES('%s', '%s', '%s')"
        for link,title in links:
            try:
                cur.execute(sql_text_2 % (code, link,title))
                self.conn.commit()
            except sqlite3.IntegrityError as e:
                if "not unique" in e.args[0]:
                    pass
                else:
                    print(f"IntegrityError insert_chapters : {link}, {title}, Cause: " + str(e))
            except Exception as e:
                print(f"ERROR: Failed insert_chapters : {link}, {title}, Cause: " + str(e))
        cur.close()

    def get_oldest_chapters(self, code):
        cur = self.conn.cursor()
        cur.execute("SELECT * FROM NOVEL WHERE CRAWLED=0 AND CODE='%s' ORDER BY LINK" % code)
        chapters = cur.fetchall()
        cur.close()
        if len(chapters)<18:
            return []
        else:
            return chapters[0:3]

    def update_chapter_status(self, id):
        cur = self.conn.cursor()
        cur.execute("UPDATE NOVEL SET CRAWLED=1 WHERE ID=%d" % id)
        self.conn.commit()
        cur.close()

    def insert_rss_item(self, title, link, enclosure_url='', pubDate=datetime.datetime.now().strftime(GMT_FORMAT), description=''):
        cur = self.conn.cursor()
        sql = "INSERT INTO RSS(TITLE,LINK, enclosure_url, pubDate, description) VALUES(?, ?, ?, ?, ?)"
        try:
            cur.execute(sql, (title,link,enclosure_url,pubDate, description))
            self.conn.commit()
        except Exception as e:
            print(f"ERROR : INSERT RSS:{link}, {title}, Cause: " + str(e))
            return False
        cur.close()
        return True

    def is_existed_rss_item(self, link):
        cur = self.conn.cursor()
        cur.execute(f"SELECT * FROM RSS WHERE LINK='{link}'")
        items = cur.fetchall()
        cur.close()
        return len(items)!=0


    def get_lastest_rss_items(self):
        cur = self.conn.cursor()
        cur.execute("select * from rss order by id desc limit 10")
        rss_items = cur.fetchall()
        cur.close()
        return rss_items

    def clean_table(self):
        cur = self.conn.cursor()
        cur.execute("delete from novel where id<((select max(id) from novel)-100)")
        cur.execute("delete from rss where id<((select max(id) from rss)-100)")
        self.conn.commit()
        cur.close()

    def close(self):
        self.conn.close()

